<template>
  <div class="custom-form">
    <el-row :gutter="15">
      <el-form
        ref="elForm"
        :model="formData"
        :rules="rules"
        size="medium"
        label-width="100px"
        :key="showFormKey"
      >
        <el-col :span="24">
          <el-form-item label-width="0" prop="field101616a">
            <h2 align='center' style="color:undefined;font-size: nullpx;text-align: center">文件传出</h2>
          </el-form-item>
        </el-col>
        <el-col :span="24" v-if="hasFormPermission('user_id')" v-show="false">
          <el-form-item :label="$t('发起人')" prop="user_id">
            <el-input
              v-model="formData['user_id']"
              placeholder="请输入发起人"
              :disabled="hasDisabledPermission('user_id', false)"
              :readonly="!hasEditPermission('user_id', true)"
              :style="{ width: '100%' }"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('申请人名称')" prop="user_name">
            <el-input v-model="formData['user_name']" placeholder="请输入申请人名称"
              :disabled="hasDisabledPermission('user_name', false)" 
              :readonly="true"
              clearable :style="{ width: '100%' }">
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('部门')" prop="depart_id">
            <el-select v-model="formData['depart_id']" placeholder="请选择部门ID"
              :disabled="hasDisabledPermission('depart_id', false)" @change="departmentChange" filterable clearable
              :style="{ width: '100%' }">
              <el-option v-for="(item, index) in departmentData" :key="index" :label="item.F_FullName"
                :value="item.F_DepartmentId" :disabled="item.disabled"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('发起人部门简称')" prop="depart_shor_name" v-show="false">
            <el-input
              v-model="formData['depart_shor_name']"
              placeholder="请输入发起人部门简称"
              :disabled="hasDisabledPermission('depart_shor_name', false)"
              :readonly="!hasEditPermission('depart_shor_name', true)"
              :style="{ width: '100%' }"
            >
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24" v-if="hasFormPermission('job')" v-show="false">
          <el-form-item :label="$t('职级名称')" prop="job">
            <el-input
              v-model="formData['job']"
              placeholder="请输入职级名称"
              :disabled="hasDisabledPermission('job', false)"
              :readonly="!hasEditPermission('job', true)"
              :style="{ width: '100%' }"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24" v-if="hasFormPermission('role_id')" v-show="false">
          <el-form-item :label="$t('角色ID')" prop="role_id">
            <el-input
              v-model="formData['role_id']"
              placeholder="请输入角色ID"
              :disabled="hasDisabledPermission('role_id', false)"
              :readonly="!hasEditPermission('role_id', true)"
              :style="{ width: '100%' }"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24" v-if="hasFormPermission('role_name')" v-show="false">
          <el-form-item :label="$t('角色名称')" prop="role_name">
            <el-input
              v-model="formData['role_name']"
              placeholder="请输入角色名称"
              :disabled="hasDisabledPermission('role_name', false)"
              :readonly="!hasEditPermission('role_name', true)"
              :style="{ width: '100%' }"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24" v-show="false">
          <el-form-item :label="$t('地区')" prop="area">
            <el-input
              v-model="formData['area']"
              placeholder="请输入地区"
              :disabled="hasDisabledPermission('area', false)"
              :readonly="!hasEditPermission('area', true)"
              :style="{ width: '100%' }"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24" v-show="false">
          <el-form-item :label="$t('是否有效')" prop="is_effective">
            <el-input
              v-model="formData['is_effective']"
              placeholder="请输入是否有效"
              :disabled="hasDisabledPermission('is_effective', false)"
              :readonly="!hasEditPermission('is_effective', true)"
              :style="{ width: '100%' }"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('文件描述')" prop="remark">
            <el-input
              v-model="formData['remark']"
              type="textarea"
              placeholder="请输入文件描述"
              :disabled="hasDisabledPermission('remark', false)"
              :readonly="!hasEditPermission('remark', false)"
              :autosize="{ minRows: 4, maxRows: 4 }"
              :style="{ width: '100%' }"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('文件传出原因')" prop="reason">
            <el-input
              v-model="formData['reason']"
              type="textarea"
              placeholder="请输入文件传出原因"
              :autosize="{ minRows: 4, maxRows: 4 }"
              :style="{ width: '100%' }"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('文件上传')" prop="tansfer_file">
            <xjr-custom-upload
              :maxFileSize="20"
              :config="tansfer_fileConfig"
              :disabled="hasDisabledPermission('tansfer_file', false)"
              v-model="formData['tansfer_file']"
              list-type="text"
            ></xjr-custom-upload>
          </el-form-item>
        </el-col>
        <el-col :span="24" v-if="hasFormPermission('suggestion')" v-show="false">
          <el-form-item :label="$t('意见簿')">
            <el-input
              v-model="formData['suggestion']"
              type="textarea"
              placeholder="请输入意见簿"
              :disabled="hasDisabledPermission('suggestion', false)"
              :readonly="!hasEditPermission('suggestion', false)"
              :autosize="{ minRows: 4, maxRows: 4 }"
              :style="{ width: '100%' }"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24" v-if="!isWorkflowForm">
          <el-form-item size="large" v-if="isEdit">
            <el-button
              type="primary"
              @click="submitForm"
              :loading="submitLoading"
            >
              {{
                submitLoading ? $t("workFlow.WFMenu.hintSubmit") : $t("submit")
              }}</el-button
            >
            <el-button @click="cancelForm">{{ $t("cancelText") }}</el-button>
          </el-form-item>
        </el-col>
      </el-form>
    </el-row>
  </div>
</template>
<script>
import FilterableDataList from "@/components/generator/clientComponents/FilterableDataList.vue";
import workflowFormAuthorize from "@/mixins/workflowFormAuthorize";
import authorizeMixin from "@/mixins/authorize";
import { baseUrl } from "@/config/env";
import request from "@/router/axios";
import { getUserDetailsById } from '@/api/user.js';
export default {
  mixins: [authorizeMixin, workflowFormAuthorize],

  components: {},
  props: ["keyValue", "isEdit", "disabled"],
  data() {
    let _this = this;
    return {
      submitLoading: false,
      showForm: true,
      showFormKey: 1,
      reRenderSubform: false,
      operationVal: "add",
      isAdd: true,
      addressUrl: "file_transfer",
      mainTableName: "oa_file_transfer",
      formConfig: {},
      formData: {
        user_name:"",
        current_user_id:"",
        user_id: "",
        depart_id: "",
        depart_shor_name: "",
        job: "",
        role_id: "",
        role_name: "",
        area: "",
        is_effective: "0",
        remark: "",
        reason: "",
        tansfer_file: null,
        suggestion: "",
      },
      rules: {
        user_id: [],
        depart_id: [
          {
            required: true,
            message: "请选择发起人部门",
            trigger: "change",
          },
        ],
        depart_shor_name: [],
        job: [],
        role_id: [],
        role_name: [],
        area: [],
        is_effective: [],
        remark: [
          {
            required: true,
            message: "请输入文件描述",
            trigger: "blur",
          },
        ],
        reason: [
          {
            required: true,
            message: "请输入文件传出原因",
            trigger: "blur",
          },
        ],
        tansfer_file: [
          {
            required: true,
            message: "文件上传不能为空",
            trigger: "change",
          },
        ],
        suggestion: [],
      },
      departmentData: [],
      roleData:[],
      tansfer_fileConfig: {
        showTip: true,
        fileSize: 20,
        sizeUnit: "MB",
        buttonText: "点击上传",
        disabled: false,
      },
    };
  },
  computed: {},
  watch: {},
  created() {
    this.formConfig = this.getFormConfig();
  },
  async mounted() {
    //TODO   再这里做数据回填 请求表单数据
    
    try {
         let userInfo = localStorage.getItem("avue-userInfo")
        ? JSON.parse(localStorage.getItem("avue-userInfo")).content
        : {};
        this.formData.current_user_id=userInfo.F_UserId;
    } catch (error) {
      
    }
 



    if (this.keyValue) {
      this.isAdd = false;
    }
    if (!this.isAdd && this.keyValue) {
      this.operationVal = "edit";
      try {
        let res = await request({
          url: baseUrl + "/" + this.addressUrl + "/" + this.keyValue,
          method: "get",
        });

        this.formData = res.data.data;

        this.showFormKey++;
      } catch (error) {}
    }
    setTimeout(() => {
      this.getCurrentInfo();
    }, 500);
  },
  methods: {
    getCurrentInfo() {
      let params = {
        userId: this.formData["current_user_id"],
      };
      getUserDetailsById(params).then((res) => {
        this.formData["user_id"] = res.data.data.F_UserId; //当前申请人id
        this.formData["user_name"] = res.data.data.F_RealName; //当前申请人姓名
        this.formData["area"] = res.data.data.F_Area; //地区
        this.formData["job"] = res.data.data.F_Job; //职级
        this.departmentData = res.data.data.F_Department;//部门信息
        this.roleData = res.data.data.F_Role; //角色信息
        this.initRole();
        this.initDepartmentData();
      });
    },
    initDepartmentData() {
      if (this.departmentData && this.departmentData.length == 1) {
        this.formData["depart_shor_name"] = this.departmentData[0].F_FullName;
        this.formData["depart_id"] = this.departmentData[0].F_DepartmentId;
      }
    },
    initRole() {
      let roleId = [];
      let roleName = [];
      if (this.roleData && this.roleData.length > 0) {
        this.roleData.forEach((e) => {
          roleId.push(e.F_RoleId);
          roleName.push(e.F_FullName);
        });
      }
      this.formData["role_id"] = roleId.join(",");
      this.formData["role_name"] = roleName.join(",");
      this.formData["apply_time"] = this.getTime();
    },
    departmentChange(val) {
      this.departmentData.forEach(ele => {
        if (val == ele.F_DepartmentId) {
          this.formData['depart_shor_name'] = ele.F_FullName
        }
      })
    },
     getTime() {
      let today = new Date()
      let year = today.getFullYear();
      let month = today.getMonth() + 1;//获取月份，值为0-11 表示1-12月份
      if (month <= 9) {
        month = "0" + month
      }
      let date = today.getDate();
      if (date <= 9) {
        date = "0" + date
      }
      let hours = today.getHours();
      if (hours <= 9) {
        hours = "0" + hours
      }
      let minutes = today.getMinutes()
      if (minutes <= 9) {
        minutes = "0" + minutes
      }
      let seconds = today.getSeconds();
      if (seconds <= 9) {
        seconds = "0" + seconds
      }
      let time = year + "-" + month + "-" + date + " " + hours + ":" + minutes + ":" + seconds
      return time
    },
    getFormData() {
      let key = this.mainTableName + "Entity";
      let returnParams = {};
      returnParams[key] = this.formData;
      return {
        ...returnParams,
      };
    },
    validateForm() {
      this.$refs["elForm"].validate((valid) => {});
    },
    async aysncValidateForm() {
      let validataArry = [];
      validataArry.push(
        new Promise((resolve, reject) => {
          this.$refs["elForm"].validate((valid) => {
            resolve(valid);
          });
        })
      );
      let res = await Promise.all(validataArry);
      if (res.includes(false)) {
        return false;
      } else {
        return true;
      }
    },
    changeTableData() {},
    async submitForm() {
      this.submitLoading = true;
      let valid = await this.aysncValidateForm();
      if (valid == false) {
        this.submitLoading = false;
        return false;
      }
      this.changeTableData();
      //格式化数据
      let newObj = this.getFormData();

      //如果没有传入参数就是新增
      if (!this.keyValue) {
        request({
          url: baseUrl + "/" + this.addressUrl,
          method: "post",
          data: newObj,
        }).then((res) => {
          this.submitLoading = false;
          this.$notify({
            title: "成功",
            message: "新增成功",
            type: "success",
          });
          this.$emit("onChange", true);
        });
      } else {
        request({
          url: baseUrl + "/" + this.addressUrl + "/" + this.keyValue,
          method: "put",
          data: newObj,
        }).then((res) => {
          this.submitLoading = false;
          this.$notify({
            title: "成功",
            message: "修改成功",
            type: "success",
          });
          this.$emit("onChange", true);
        });
      }
    },
    cancelForm() {
      this.$emit("onChange", true);
    },
    formatTree(data, valueField, lableField, childField, type) {
      let tree = [];
      data.forEach((node, index) => {
        let newNode = {
          value: node[valueField],
          label: node[lableField],
        };
        if (type) {
          newNode.disabled = node[valueField] == undefined ? true : false;
        }
        tree.push(newNode);
        if (node[childField] != null && node[childField].length > 0) {
          newNode.children = this.formatTree(
            node[childField],
            valueField,
            lableField,
            childField,
            type
          );
        }
      }, this);
      return tree;
    },

    //辅助工作流 审批(编辑) 预留方法
    handleEdit() {},

    //子表单权限
    getAuthorityTableChildrenList(bindTable, children) {
      let column = [];
      if (bindTable && this.formEnCodeList && this.formEnCodeList[bindTable]) {
        let formSubEnCodeList = this.formEnCodeList[bindTable];
        if (children && children.length > 0) {
          column = children.map((ele2) => {
            if (formSubEnCodeList.includes(ele2.prop)) {
              ele2.hide = false;
            } else {
              ele2.hide = true;
            }
            if (ele2.hide == false) {
              //工作流中系统表单必填权限
              if (this.formSubTableNotRequiredList[bindTable] != undefined) {
                if (
                  this.formSubTableNotRequiredList[bindTable].includes(
                    ele2.prop
                  )
                ) {
                  ele2.required = false;
                } else {
                  ele2.required = true;
                }
              }
              ele2.rules = [];
              if (ele2.required) {
                ele2.rules = ele2.ruleList;
              }
              // disabled 属性
              if (this.formSubTableDisabledList[bindTable] != undefined) {
                if (
                  this.formSubTableDisabledList[bindTable].includes(ele2.prop)
                ) {
                  ele2.disabled = true;
                } else {
                  ele2.disabled = false;
                }
              }
            }
            return ele2;
          });
        }
        return column;
      } else {
        return children;
      }
    },
    getFormConfig() {
      let config = {
        fields: [
          {
            __vModel__: "user_id",
            __config__: {
              label: "发起人",
              showLabel: true,
              tag: "el-input",
              avueType: "input-tip",
              required: false,
              span: 24,
              F_LgMarkCode: "",
              prestrainField: "",
              formId: 100,
              fieldLength: "50",
              bindTable: "oa_file_transfer",
              bindTableField: "user_id",
              bindTableFieldType: "varchar",
            },
          },
          {
            __vModel__: "depart_id",
            __config__: {
              label: "发起人部门",
              showLabel: true,
              tag: "el-select",
              avueType: "select",
              span: 24,
              required: true,
              saveField: "",
              showField: "",
              F_LgMarkCode: "",
              prestrainField: "",
              formId: 102,
              fieldLength: "50",
              bindTable: "oa_file_transfer",
              bindTableField: "depart_id",
              bindTableFieldType: "varchar",
            },
          },
          {
            __vModel__: "depart_shor_name",
            __config__: {
              label: "发起人部门简称",
              showLabel: true,
              tag: "el-input",
              avueType: "input-tip",
              required: false,
              span: 24,
              F_LgMarkCode: "",
              prestrainField: "",
              formId: 101,
              fieldLength: "50",
              bindTable: "oa_file_transfer",
              bindTableField: "depart_shor_name",
              bindTableFieldType: "varchar",
            },
          },
          {
            __vModel__: "job",
            __config__: {
              label: "职级名称",
              showLabel: true,
              tag: "el-input",
              avueType: "input-tip",
              required: false,
              span: 24,
              F_LgMarkCode: "",
              prestrainField: "",
              formId: 104,
              fieldLength: "50",
              bindTable: "oa_file_transfer",
              bindTableField: "job",
              bindTableFieldType: "varchar",
            },
          },
          {
            __vModel__: "role_id",
            __config__: {
              label: "角色ID",
              showLabel: true,
              tag: "el-input",
              avueType: "input-tip",
              required: false,
              span: 24,
              F_LgMarkCode: "",
              prestrainField: "",
              formId: 107,
              fieldLength: 500,
              bindTable: "oa_file_transfer",
              bindTableField: "role_id",
              bindTableFieldType: "varchar",
            },
          },
          {
            __vModel__: "role_name",
            __config__: {
              label: "角色名称",
              showLabel: true,
              tag: "el-input",
              avueType: "input-tip",
              required: false,
              span: 24,
              F_LgMarkCode: "",
              prestrainField: "",
              formId: 106,
              fieldLength: 500,
              bindTable: "oa_file_transfer",
              bindTableField: "role_name",
              bindTableFieldType: "varchar",
            },
          },
          {
            __vModel__: "area",
            __config__: {
              label: "地区",
              showLabel: true,
              tag: "el-input",
              avueType: "input-tip",
              required: false,
              span: 24,
              F_LgMarkCode: "",
              prestrainField: "",
              formId: 105,
              fieldLength: "50",
              bindTable: "oa_file_transfer",
              bindTableField: "area",
              bindTableFieldType: "varchar",
            },
          },
          {
            __vModel__: "is_effective",
            __config__: {
              label: "是否有效",
              showLabel: true,
              tag: "el-input",
              avueType: "input-tip",
              required: false,
              span: 24,
              F_LgMarkCode: "",
              prestrainField: "",
              formId: 103,
              fieldLength: "50",
              bindTable: "oa_file_transfer",
              bindTableField: "is_effective",
              bindTableFieldType: "varchar",
            },
          },
          {
            tempType: "textarea",
            __vModel__: "remark",
            __config__: {
              label: "文件描述",
              showLabel: true,
              tag: "el-input",
              avueType: "textarea",
              required: true,
              span: 24,
              F_LgMarkCode: "",
              prestrainField: "",
              formId: 108,
              fieldLength: "100",
              bindTable: "oa_file_transfer",
              bindTableField: "remark",
              bindTableFieldType: "varchar",
            },
          },
          {
            tempType: "textarea",
            __vModel__: "reason",
            __config__: {
              label: "文件传出原因",
              showLabel: true,
              tag: "el-input",
              avueType: "textarea",
              required: true,
              span: 24,
              F_LgMarkCode: "",
              prestrainField: "",
              formId: 109,
              fieldLength: "100",
              bindTable: "oa_file_transfer",
              bindTableField: "reason",
              bindTableFieldType: "varchar",
            },
          },
          {
            __vModel__: "tansfer_file",
            __config__: {
              label: "文件上传",
              tag: "el-upload",
              avueType: "upload",
              defaultValue: null,
              showLabel: true,
              required: true,
              span: 24,
              showTip: true,
              buttonText: "点击上传",
              fileSize: 20,
              sizeUnit: "MB",
              F_LgMarkCode: "",
              prestrainField: "",
              formId: 110,
              fieldLength: "200",
              bindTable: "oa_file_transfer",
              bindTableField: "tansfer_file",
              bindTableFieldType: "varchar",
            },
          },
          {
            tempType: "textarea",
            __vModel__: "suggestion",
            __config__: {
              label: "意见簿",
              showLabel: true,
              tag: "el-input",
              avueType: "textarea",
              required: false,
              span: 24,
              F_LgMarkCode: "",
              prestrainField: "",
              formId: 111,
              fieldLength: "100",
              bindTable: "oa_file_transfer",
              bindTableField: "suggestion",
              bindTableFieldType: "varchar",
            },
          },
        ],
      };
      return config;
    },
  },
};
</script>
<style>
.el-table__empty-block {
  width: 100% !important;
}

.avue-form__row {
  padding: 0 !important;
}

#editorphone {
  width: 375px;
  margin: 0 auto;
  border: 1px solid #e4e7ed;
  padding: 0 7.5px;
  background: #f5f6fa;
  height: 700px;
  overflow-y: auto;
  overflow-x: hidden;
  border-radius: 5px;
}

#editorphone .el-col {
  border-bottom: 1px solid #f2f2f2;
  background: #fff;
  margin-bottom: 0;
  padding: 0 15px 6px !important;
  width: 100%;
}

#editorphone .el-form-item__label {
  line-height: 20px;
}

#editorphone .el-input-group .el-input__inner {
  background: #f5f6fa;
}

#editorphone .el-input__inner {
  border: 0;
}

#editorphone .el-input-group__append,
#editorphone .el-input-group__prepend {
  border: 0;
  background: #edeef2;
  color: #666;
}

#editorphone .el-input-group .el-input__prefix {
  left: 44px;
}

#editorphone .el-input-group .el-input__suffix {
  right: 44px;
}

#editorphone .el-form-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  flex-flow: wrap;
}

#editorphone .el-form-item__label {
  float: none;
  min-width: 85px;
  width: auto !important;
  text-align: left;
  flex: auto;
}

#editorphone .tinymce .el-form-item__label {
  min-width: 100%;
}

#editorphone .el-form-item__content {
  margin-left: 0px !important;
  flex: auto;
  width: calc(100% - 95px);
}

#editorphone .avueFormNoLable .el-form-item__label,
#editorphone .avueFormNoLable .avue-crud__pagination {
  display: none;
}

#editorphone .avueFormNoLable .el-collapse-item__wrap,
#editorphone .avueFormNoLable .el-collapse {
  border-bottom: 0;
}

#editorphone .avueFormNoLable .el-col {
  border-bottom: 0;
  padding-bottom: 0;
}

#editorphone .el-form-item__content .el-button:first-child {
  margin-left: 90px;
}

.el-upload__tip {
  line-height: 1.2;
}
</style>
